package com.hl.card.credit.pub.common;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 执行器，{@link com.tbs.common.utils.redis.RedisUtil}的辅助类，
 * 它保证在执行操作之后释放数据源returnResource(jedis)
 * @author wdf
 * @param <T>
 */
public abstract class Executor<T> {
	Jedis jedis;
	JedisPool jedisPool;

	public Executor(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
		jedis = this.jedisPool.getResource();
	}

	/**
	 * 回调
	 * @param <T>
	 * @return 执行结果
	 */
	abstract  T execute();

	/**
	 * 调用{@link #execute()}并返回执行结果
	 * 它保证在执行{@link #execute()}之后释放数据源returnResource(jedis)
	 * @return 执行结果
	 */
	public T getResult() {
		T result = null;
		try {
			result = execute();
		} catch (Throwable e) {
			System.out.println("返回连接池资源,数据为空(execute())会输出:Could not return the resource to the pool");
			jedisPool.returnBrokenResource(jedis);
			throw new RuntimeException("Redis execute exception", e);
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
		return result;
	}
}
